package com.salestax.core.io;

import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.salestax.core.Product;
import com.salestax.core.ShoppingList;
import com.salestax.core.factory.ProductFactory;

public class ShoppingListReader {

	private Reader inputReader;

	public ShoppingList getShoppingListFromReader() {
		ShoppingList shoppingList = new ShoppingList();
		Collection<Product> prods = new ArrayList<Product>();
		Scanner scanner = new Scanner(inputReader).useDelimiter("\n");
		Pattern pattern = Pattern
				.compile("(\\d+)\\s([\\w\\s]+)\\s([0-9]*\\.?[0-9]+)");
		while (scanner.hasNext()) {
			String nextLine = scanner.next().trim();
			System.out.println(nextLine);
			Matcher matcher = pattern.matcher(nextLine);
			matcher.find();
			if (validProductDescription(matcher)) {
				String quantity = matcher.group(1);
				String description = matcher.group(2);
				String basePrice = matcher.group(3);
				prods.add(ProductFactory.createProduct(description, Double.valueOf(basePrice),Integer.valueOf(quantity)));
			}
		}
		for(Product product:prods){
			shoppingList.addProduct(product);
		}
		return shoppingList;
	}

	private boolean validProductDescription(Matcher matcher) {
		return matcher.matches() && matcher.groupCount() == 3;
	}

	public ShoppingListReader(Reader inputReader) {
		super();
		this.inputReader = inputReader;
	}

}
